package com.example.iorder.restaurant;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.domain.Restaurant;
import com.example.iorder.R;
import com.example.iorder.config.Config;
import com.example.iorder.reservation.SelectDateAndTime;
import com.example.iorder.util.HTTPClient;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class RestaurantDetails_GeneralInformation extends Activity {
	private ProgressDialog progress;
	
	protected void onCreate(Bundle savedInstanceState) 
	{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.restaurant_details_generalinformation);

        this.setTitle("iOrder | General Information");
        
        // Show loading indicator
        progress = new ProgressDialog(this);
        progress.setTitle(getResources().getString(R.string.loading_title));
        progress.setMessage(getResources().getString(R.string.loading_message));
        progress.show();
        
        Bundle reservationInfo = getIntent().getExtras();
        final int restId = reservationInfo.getInt(getResources().getString(R.string.key_restaurant_id));
        
        // Start another thread to search for restaurants
        new Thread() {
        	public void run() {
        		Message msg = new Message();
        		String path = "";
        		HTTPClient httpClient = null;
        		String searchResult = "";
        		int restaurantId = restId;
        		
        		try {
        			path = Config.URL_RESTAURANTS + restaurantId;
        			httpClient = new HTTPClient(getBaseContext());
        			searchResult = httpClient.sendGETRequest(Config.IORDER_SERVER, path);
        			
        			msg.getData().putString("searchResult", searchResult);
        			searchOutputHandler.sendMessage(msg);
        		} catch (Exception e) {
        			msg.getData().putString("exception", e.toString());
        		}
        	}
        }.start();
    }
	
	@SuppressLint("HandlerLeak")
	private Handler searchOutputHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			String newData = msg.getData().getString("searchResult");
			JSONObject record = null;
			//ArrayList<Restaurant> list = new ArrayList<Restaurant>();
			progress.dismiss();
			
			try 
			{
				JSONObject jsonObject = new JSONObject(newData);
				if (jsonObject.has("data") && jsonObject.has("msg") && jsonObject.has("status")) 
				{
					// Connection to server was successful and data was received 
					if (jsonObject.get("status").toString().equals("200")) 
					{
						record = jsonObject.getJSONObject("data");

						try 
						{
									String restaurantIdString = record.optString("ID");
									String restaurantName = record.optString("Name");
									String restaurantAddress = record.optString("Address");
									String restaurantCity = record.optString("City");
									String restaurantPhoneNumber = record.optString("PhoneNumber");
									String restaurantWebSite = record.optString("Website");
									String restaurantDescription = record.optString("Description");
									String restaurantEmailAddress = record.optString("EmailAddress");
									int id = Integer.parseInt(restaurantIdString);
									
										//(int id, String name, String address, String city, String phoneNumber, String kitchen)
									Restaurant newRestaurant = new Restaurant(id, restaurantName, restaurantAddress, restaurantCity, restaurantPhoneNumber, restaurantWebSite, restaurantDescription, restaurantEmailAddress, "");
						
									TextView guiName = (TextView) findViewById(R.id.restaurant_name_data);
									TextView guiAddress = (TextView) findViewById(R.id.restaurant_address_data);
									TextView guiCity = (TextView) findViewById(R.id.restaurant_city_data);
									TextView guiPhoneNumber = (TextView) findViewById(R.id.restaurant_phonenumber_data);
									TextView guiWebSite = (TextView) findViewById(R.id.restaurant_website_data);
									TextView guiEmailAddress = (TextView) findViewById(R.id.restaurant_email_address_data); 
									TextView guiDescription = (TextView) findViewById(R.id.restaurant_description_data);

									guiName.setText(RestaurantDetails_GeneralInformation.validateString(restaurantName));
									guiAddress.setText(RestaurantDetails_GeneralInformation.validateString(restaurantAddress));
									guiCity.setText(RestaurantDetails_GeneralInformation.validateString(restaurantCity));
									guiPhoneNumber.setText(RestaurantDetails_GeneralInformation.validateString(restaurantPhoneNumber));
									guiWebSite.setText(RestaurantDetails_GeneralInformation.validateString(restaurantWebSite));
									guiEmailAddress.setText(RestaurantDetails_GeneralInformation.validateString(restaurantEmailAddress));
									guiDescription.setText(RestaurantDetails_GeneralInformation.validateString(restaurantDescription));
																	
						} 
						catch (Exception e) 
						{
						}						
					}//if (jsonObject.get("sta

//					} else {
//						Toast.makeText(getBaseContext(), "Backend server error no : " + jsonObject.get("status").toString(), Toast.LENGTH_SHORT).show();
//						progress.dismiss();
//					}
				} 
				else 
				{
					Toast.makeText(getBaseContext(), "Faulty backend server response!", Toast.LENGTH_SHORT).show();
					progress.dismiss();
				} // if (jsonObject.has("da...
			} 
			catch (JSONException jsnE) 
			{
				String errorMessage = "JSON Error: " + jsnE.getMessage();
				if (newData.equals("Error: No network")) 
				{
					errorMessage = getResources().getString(R.string.no_network_connection);
				}
				Toast.makeText(getBaseContext(), errorMessage, Toast.LENGTH_LONG).show();
				progress.dismiss();
			} 
			catch (Exception e) 
			{
				Toast.makeText(getBaseContext(), "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
				progress.dismiss();
			}
		} // public void handleMe
	}; // private Handler search...
	
	public static String validateString(String restData)
	{
		if(restData != null)
			return restData;
		else
			return restData;
	}
	
	public void startReservation(View view)
	{
		Intent intent = new Intent(RestaurantDetails_GeneralInformation.this, SelectDateAndTime.class);
		intent.putExtras(getIntent().getExtras());
		startActivity(intent);
	}
}
